package com.pengpeng.zookeeper.config;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author 彭鹏
 * @date 2021/10/21.
 */
@Configuration
public class ZookeeperConfig {

    //zookeeper连接信息
    @Value("${zookeeper.connect.address:}")
    private String connectStr;
    //session超时时间(毫秒)
    @Value("${zookeeper.connect.time-out:}")
    private int timeOut;
    private CountDownLatch connectLatch = new CountDownLatch(1);
    ZooKeeper zkClient;
    /**
     * 初始化zookeeper连接
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @Bean
    public ZooKeeper getZkClient() throws IOException, InterruptedException {
        zkClient = new ZooKeeper(connectStr, timeOut, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event);
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    connectLatch.countDown();
                }
                try {
                    getServerList();
                } catch (KeeperException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        connectLatch.await();
        return zkClient;
    }
    private void getServerList() throws KeeperException, InterruptedException {
        List<String> children = zkClient.getChildren("/servers", true);

        ArrayList<String> servers = new ArrayList<>();

        for (String child : children) {

            byte[] data = zkClient.getData("/servers/" + child, false, null);

            servers.add(new String(data));
        }

        // 打印
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +"-------" + servers);
    }
}